import { Component } from 'react';

import Form from './form';
import SubForm from './subForm';
import CommentList from 'components/comment_list';
let FlowCommon ;
export default class PageHome extends Component {
	constructor(props) {
		super(props);

		// let startUserName = decodeURI(this.props.params.startUserName);//创建人用户
		// let startUserGroupName = decodeURI(this.props.params.startUserGroupName);//创建人组织
		//let startUserId = this.props.params.startUserId;
		
		this.state = {
			commentFieldList:[],
			commentDefaultList:[],
			//startUserId:startUserId,
			formItem:[],
			formData:{},
			
		};
		
		FlowCommon = require('pages/flow_common/'+props.module);
       
	}

	componentDidMount() {
		let t = this;
		// let formItem = this.props.form;
		// let commentList = this.props.commentList;
		// let formData = this.props.formData;
		
		// t.setState({
		// 	formItem:formItem,
		// 	commentFieldList:commentFieldList,
		// 	commentDefaultList:commentDefaultList,
		// 	formData:formData
		// });
	}





	change(data,itemParam){
		if(itemParam){//修改事件的时候
			 //处理特有参数
			if(typeof FlowCommon.dealwithFormItemChange === "function"){
				FlowCommon.dealwithFormItemChange(itemParam,this);
			}
			var uniqueName = itemParam.uniqueName;
			if(itemParam.itemType=='text' || itemParam.itemType == 'datetime'){//当等于单行文本或者时间时
				var calculateExpList = data.calculateExpList;//计算公式列表
				if(calculateExpList){
				var calculateExpValue = calculateExpList[itemParam.uniqueName];
					if(calculateExpValue){
						if(Array.isArray(calculateExpValue)){
							for(var i=0; i<calculateExpValue.length; i++){
								var exp = calculateExpValue[i].exp;//计算公式
								var resultItem = calculateExpValue[i].result; //当前修改字段的uniqname,如：test_mobileform_sz2
								var resultKey = calculateExpValue[i].key; //当前修改字段的code,如：sz2
								var fieldArray = this.getFieldArray(exp);//获取计算公式参与的字段
								var fieldItemArray = [];//计算公式所有参与的字段itemParam
								for(var j=0; j<fieldArray.length; j++){
									var fieldArrayItem = fieldArray[j];
									var fieldItem = null;
									if(this.refs[fieldArrayItem]){//当字段是主表时
										fieldItem = this.refs[fieldArrayItem].getItemParam();
									}else{
										var subTableName = this.getSubRef(fieldArrayItem);
										if(subTableName != "" && this.refs['sub_'+subTableName]){//当字段是子表时
											fieldItem = this.refs['sub_'+subTableName].getSubItemParam(fieldArrayItem);
										}
									}
									if(fieldItem != null){
										var filedItemValue = "";
										if(Array.isArray(fieldItem)){//当是数组时，代表是子表
											if(fieldItem.length>0){
												fieldItemArray.push(fieldItem[0]);
												filedItemValue = fieldItem[0].value;
											}
										}else{
											fieldItemArray.push(fieldItem);
											filedItemValue = fieldItem.value;
										}

										if(itemParam.itemType == 'datetime'){//当为时间时且有differDate或者differHour函数
											var differDateRegExp = new RegExp("differDate\\(","g");
											var differHourRegExp = new RegExp("differHour\\(","g");
											if(exp.match(differDateRegExp) || exp.match(differHourRegExp)){//当有differDate函数
												if(typeof filedItemValue == 'undefined' || filedItemValue=="" || filedItemValue == null){
													//filedItemValue = 0;
													return false;
												}else{
													filedItemValue = filedItemValue.value;
												}
											}
										}

										if(typeof filedItemValue == 'undefined' ||filedItemValue == "" ||filedItemValue==null){//当filedItemValue为空或者其他异常状态时置为0
											//filedItemValue=0;
											return false;
										}
										var sumRegExp = new RegExp("sum\\(\\["+fieldArrayItem+"\\]\\)","g");

										if(exp.match(sumRegExp)){//当有sum函数
											if(Array.isArray(fieldItem)){
												var sumValue = this.sum(fieldItem);
												exp=exp.replace(new RegExp("sum\\(\\["+fieldArrayItem+"\\]\\)","g"),sumValue);
											}
										}

										exp=exp.replace(new RegExp("\\["+fieldArrayItem+"\\]","g"),filedItemValue);
									}
								}
								
								exp=exp.replace(new RegExp("rmb\\(","g"),'calculate.rmb(');
								exp=exp.replace(new RegExp("differDate\\(","g"),'calculate.differDate(');
								exp=exp.replace(new RegExp("differHour\\(","g"),'calculate.differHour(');
								var res=eval(exp);
								// if(res == Infinity){//无穷大
								// 	res = 0 ;
								// }
								if(typeof(res)=='number'){
									if(isNaN(res)){//结果不为数字  则置为0
										res=0;
									}else{
										var fieldType=itemParam.inputFormat;
										if(fieldType=='int'||fieldType=='float'){
											res=Number(res).toFixed(itemParam.decimalPlace);
										}else{
											if(fieldArray.length==0){
												var aDP=getActualDecimalPlace(exp);
												res=res.toFixed(aDP);
											}else{
												var maxDP= getMaxDecimalPlace(fieldItemArray);//获取参与计算的字段中 最长的小数位
												res=res.toFixed(maxDP);
											}
										}
									}	
								}
								var resultMap = {};
								resultMap.key = 'value';
								resultMap.value = res;
								this.refs[resultItem].reloadItemParam([resultMap]);
								data = this.editData(resultKey,res,data);
							}
						}
					}
				}
				
			}
		}
		this.props.onChange(data);
	}

	//检查是不是子表的字段，如果是获取子表的表名
	getSubRef(field){
		var code = "";
		this.props.form.map(function(item){
			if(item.itemType == 'detail'){//子表时
				item.children.map(function(item1){
					if(field == item1.uniqueName){
						code = item.itemCode;
						return false;
					}
				});
			}
		});
		return code;
	}

	sum(fieldItem){//eval运算时  对字段值进行求和运算
		var val=0;
		var len=fieldItem.length;
		for(var i=0;i<len;i++){
			var curVal = fieldItem[i].value;
			if(typeof curVal == 'undefined' || curVal == '' || curVal == null){
				curVal = 0;
			}
			val+=Number(curVal+'');//转字符串  否则以0开头会被当做八进制计算 以0x开头会被当做十六进制处理
		}
		if(isNaN(val)){//结果不为数字  则置为0
			val=0;
		}
		return val;
	}

	//从计算表达式中获取涉及的字段
	getFieldArray(exp){
		var fieldArray=[];
		var expProcessStepOne=exp.split('[');
		for(var i=1;i<expProcessStepOne.length;i++){
			var expProcessStepTwo=expProcessStepOne[i].split(']');
			if(expProcessStepTwo.length>0){
				var fieldUniqueName=expProcessStepTwo[0];
				if(fieldUniqueName.length>0){
					fieldArray.push(fieldUniqueName);
				}
			}
		}
		return fieldArray;
	}
	//给定一个表达式   获取参与计算的浮点型数据中小数位最长的数据
	getActualDecimalPlace(exp){
		var actualDP=0;
		var floatReg=/\d+(\.\d+)?/g;
		var numArray=exp.match(floatReg);
		for(var i=0;i<numArray.length;i++){
			var numSplit=numArray[i].split('.');
			if(numSplit.length>1){
				if(numSplit[1].length>actualDP){
					actualDP=numSplit[1].length;
				}
			}
		}
		return actualDP;
	}

	//获取涉及计算字段中最长的小数位
	getMaxDecimalPlace(fieldItemArray){
		var maxDP=0;
		for(var j=0;j<fieldItemArray.length;j++){//遍历表单所有整型和浮点型字段
				if(fieldItemArray[j].decimalPlace>maxDP){
					maxDP=fieldItemArray[j].decimalPlace;//取最长的小数位
				}
		}
		return maxDP;
	}

	//修改data数据
	editData(itemCode,value,data){
		if(Array.isArray(itemCode) && Array.isArray(value)){//数组时
		  for(var i=0; i<itemCode.length; i++){
			var mainTblData = data.mainTblData;
			mainTblData.map(function(item,index){
			  if(item.key==itemCode[i]){
				item.value = value[i];
			  }
			});
		  }
		
		}else{
		  var mainTblData = data.mainTblData;
		  mainTblData.map(function(item,index){
			if(item.key==itemCode){
			  item.value = value;
			}
		  });
		}
	  
	  return data;
	}

	

	render() {
		const t = this;
		return (
			<div >
				<div>
				{
					this.props.form.map(function(item,i){
					return (
							item.itemType=='twocolumns'|| item.itemType=='threecolumns' ?
							item.children.map(function(item2,j){
							return (
								<div><Form keyNo={j} ref={item.uniqueName}  module={t.props.module} status={t.props.status} form={item2} commentList={t.props.commentFieldList} data={t.props.data} fieldControll={t.props.fieldControll}  onChange={this.change.bind(this)}/></div>
							)}.bind(this))
							:item.itemType=='detail'?
							<div><SubForm keyNo={i} ref={'sub_'+item.itemCode}  module={t.props.module} status={t.props.status} form={item} commentList={t.props.commentFieldList} data={t.props.data} fieldControll={t.props.fieldControll}  onChange={this.change.bind(this)}/></div>
							:<div><Form ref={item.uniqueName} keyNo={i}  module={t.props.module} status={t.props.status} form={item} commentList={t.props.commentFieldList} data={t.props.data} fieldControll={t.props.fieldControll}  onChange={this.change.bind(this)}/></div>
						
						)}.bind(this))
				}
				</div>
				<div className={t.props.commentDefaultList.length>0?"t-H10 t-BCf7":'t-DN'}></div>
				<div className={t.props.commentDefaultList.length>0?'':'t-DN'} >
					<div className="t-field-layout-v-label t-FS16">批示意见</div>
					<CommentList list={t.props.commentDefaultList}/> 
				</div>
			</div>
		)
	}
}
